
package org.itboys.mobile.service.mongo.front;

import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dto.count.SundayCountDto;
import org.itboys.mobile.dto.count.SundayCountProductDto;
import org.itboys.mobile.dto.count.SundayCountTotalDto;
import org.itboys.mobile.dto.product.SundayProductDto;
import org.itboys.mobile.entity.mongo.SundayCart;
import org.itboys.mobile.entity.mysql.product.SundayProduct;
import org.itboys.mobile.service.mysql.front.SundayFrontProductService;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseMongoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;


/**
 * 作者：jiangxiong
 * 日期：2017年5月8日
 * 联系方式 ：empty90911@126.com
 * 描述：圣代_购物车_service_移动端
 */

@Service
public class SundayFrontCartService extends BaseMongoService<SundayCart> {
    @Autowired
    private SundayFrontProductService productService;
    @Autowired
    private SundayFrontMemberService memberService;


    @Resource(name = "mobileDs")
    private MongoDataSource mobileDataSource;
    @Override
    protected MongoDataSource getMongoDataSource() {
        return mobileDataSource;
    }

    @Override
    protected Class<SundayCart> getEntityClass() {
        return SundayCart.class;
    }


/**
     * 新增购物车（支持批量新增）。
     * @param memberId
     * @param productIds
     * @param nums
     * @param cartType 1,通过购物车加入的；2，通过立即购买加入的
     * @return
     */
    public  List<Long> addCart(Long memberId,List<Long> productIds ,List<Integer> nums,Integer cartType){



        if(ListUtil.isNull(productIds)|| ListUtil.isNull(nums)||(productIds.size()!=nums.size())){
            throw new ErrorException("传入参数错误");
        }
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("ids",productIds);
        List<SundayProduct> products = productService.select(param);
        //如果是立即购买加入购物车，先删除原来购物车中立即购买加入的数据
        if(cartType== SundayCommonConstants.cart_type_buy_now){
            deleteCart(null,memberId, SundayCommonConstants.cart_type_buy_now);
         //加入购物车方式,判断类型
        }else{
            Integer type =products.get(0).getType();
            if(type!=SundayCommonConstants.type_putong&&
                    type!=SundayCommonConstants.type_xinpin&&
                    type!=SundayCommonConstants.type_temai&&
                    type!=SundayCommonConstants.type_haitao&&
                    type!=SundayCommonConstants.type_fenxiao){
                throw new ErrorException("此商品类型不能加入购物车");
            }

        }
            //返回结果
        List<Long> cartIds = new ArrayList<Long>();
        //获取要加入的商品

        //旧购物车数据
         param.clear();
        param.put("memberId",memberId);
        param.put("isDeleted",0);
        param.put("cartType",cartType);

        List<SundayCart> oldCarts=super.list(param);
        List<SundayCart> needToAdd=new ArrayList<SundayCart>();

        //比对出哪一些商品是需要新增的，哪一些是增加数量的
        for(int i=0;i< products.size();i++){
            SundayProduct product = products.get(i);
            Integer num =nums.get(i);
            boolean isExist=false;
            for(SundayCart oldCart:oldCarts){
                if(oldCart.getProductId().longValue()==product.getId().longValue()){
                    isExist=true;
                    super.update(oldCart.getId(),"num",num+oldCart.getNum());
                    break;
                }
            }
            //本次需要新增的商品
            if(!isExist){
                needToAdd.add(new SundayCart(memberId, product.getId(), num,cartType));
            }
        }
        if(ListUtil.isNotNull(needToAdd)){
            super.batchSave(needToAdd);
        }
        for(SundayCart needToAd:needToAdd){
            cartIds.add(needToAd.getId());
        }
        return cartIds;

    }


/**
     * 修改购物车数量，支持批量修改
     * @param memberId
     * @param cartIds
     * @param nums
     */

    public void updateCart(Long memberId ,List<Long> cartIds ,List<Integer> nums){
        if(ListUtil.isNull(cartIds)|| ListUtil.isNull(nums)||(cartIds.size()!=nums.size())){
            throw new ErrorException("传入参数错误");
        }
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("id in",cartIds);
        param.put("memberId",memberId);
        param.put("isDeleted",0);
        List<SundayCart> carts = super.list(param);
        List<SundayCart> isNeedToUpdate= new ArrayList<>();
        for(int i=0;i<carts.size();i++){
            SundayCart cart = carts.get(i);
            Integer num = nums.get(i);
            //数量变更后才操作数据库。执行修改
            if(cart.getNum()!=num){
                cart.setNum(num);
                isNeedToUpdate.add(cart);
            }
        }
        if(ListUtil.isNotNull(isNeedToUpdate)){
            super.batchUpdateWithoutLogin(isNeedToUpdate);
        }
    }

/**
     * 删除购物车，支持批量删除
     * @param cartIds
     * @param memberId
     * @param cartType
     */

    public void deleteCart(List<Long> cartIds ,Long memberId,Integer cartType){
        Map<String,Object> param = new HashMap<String,Object>();
        if(ListUtil.isNotNull(cartIds)){
            param.put("id in",cartIds);
        }
        param.put("memberId",memberId);
        param.put("isDeleted",SundayCommonConstants.NO);
        if(cartType!=null){
            param.put("cartType",cartType);
        }
        super.delete(param);
    }



    /**
     * 获取购物车。不分页。
     * @param memberId
     * @param cartIds 结算/生成订单时传入此参数/手机端合计购物车商品价格（如系统含有满减，x元任选等促销手段）
     * @param cartType 1,通过购物车加入的；2，通过立即购买加入的

     * @return
     */
    public SundayCountTotalDto getCart(Long memberId, List<Long> cartIds, Integer cartType){
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("memberId",memberId);
        param.put("isDeleted",0);

        if(ListUtil.isNotNull(cartIds)){
            param.put("id in",cartIds);
        }else{
            cartIds=new ArrayList<>();
        }
        if(cartType!=null){
            param.put("cartType",cartType);
        }


        List<SundayCart> carts = super.list(param);
        //购物车外层数据。总价
        SundayCountTotalDto countTotalDto = new SundayCountTotalDto();

        if(ListUtil.isNull(carts))return countTotalDto;
        //对应的商品数据
        List<Long> productIds = new ArrayList<Long>();
        for(SundayCart cart:carts){
            productIds.add(cart.getProductId());
        }
        param.clear();
        param.put("ids",productIds);
        List<SundayProduct> products = productService.select(param);
        List<SundayProductDto> productDtos = productService.packageDtoMuilt(products);

        //商品中门店的ID集合
        Set<Long> shopIds = new HashSet<Long>();
        for(SundayProduct product:products){
            shopIds.add(product.getShopId());
        }
        /*for(Long shopId:shopIds){
            logger.info("本次结算共有门店ID="+shopId);
        }*/
        //购车车ID集合
       // StringBuilder cartIdsSb = new StringBuilder();
        //通过购物车和商品信息匹配对应的商品信息

        List<SundayCountProductDto> countProductDtos =new ArrayList<>();
        for(SundayCart cart:carts){
            for(SundayProductDto productDto:productDtos){
                if(cart.getProductId().longValue()==productDto.getId()){
                    SundayCountProductDto countProductDto = new SundayCountProductDto(
                                    productDto.getId(), productDto.getCreateTime(), productDto.getCreateDate(),
                            cart.getId(), productDto.getName(), productDto.getBarCode(),productDto.getImage(),
                                    cart.getNum(),productDto.getStandard(),productDto.getStatus(),productDto.getStore(),
                            productDto.getPrice(),productDto.getMarketPrice(),productDto.getType(),productDto.getSaleNumber(),
                            productDto.getShopId(),productDto.getShopName(),productDto.getShopImage(),productDto.getShopDesc(),productDto.getIsDiscount());
                    //2018年1月21日，根据商品类型，增加一些信息
                    countProductDto.setTax(productDto.getTax());
                    countProductDto.setTaxMsg(productDto.getTaxMsg());
                    countProductDto.setSecKillTimeGroupValue(productDto.getSecKillTimeGroupValue());
                   // countProductDto.setse
                    countProductDto.setTeamPrice(productDto.getTeamPrice());
                    countProductDtos.add(countProductDto);
                    break;
                }
                if(ListUtil.isNull(cartIds)){
                    cartIds.add(cart.getId());
                }
                //cartIdsSb.append(String.valueOf(cart.getId()).toString()+",");
            }
        }
       // logger.info("-------------"+countProductDtos.size());
        //购物车，结算时，以门店区分开
        List<SundayCountDto> countDtos=new ArrayList<>();
        for(Long shopId:shopIds){
            logger.info("结算实体类中门店ID="+shopId);
            SundayCountDto countDto =new SundayCountDto();
            List<SundayCountProductDto> countProducts =new ArrayList<>();
            Double totalAmount = 0.00;
            Double payAmount =0.00;
            String shopName=null;
            String shopImage="";
            for(SundayCountProductDto countProductDto:countProductDtos){
            //    logger.info("-商品门店ID======"+countProductDto.getShopId());
                if(shopId.longValue()==countProductDto.getShopId().longValue()){
                    totalAmount+=countProductDto.getPrice().doubleValue()*countProductDto.getNum();
                    payAmount+=countProductDto.getPrice().doubleValue()*countProductDto.getNum();
                    countProducts.add(countProductDto);
                    shopName=countProductDto.getShopName();
                    shopImage=countProductDto.getShopImage();
                }
            }
            //获取当前购物车的类型。1普通，2新品，3特卖，4海淘，5分销，6爱购币，7积分，8秒杀，9拼团，10试用
            countDto.setType(countProducts.get(0).getType());
            countDto.setTotalAmount(new BigDecimal(totalAmount).setScale(2,BigDecimal.ROUND_HALF_UP));
            countDto.setPayAmount(new BigDecimal(payAmount).setScale(2,BigDecimal.ROUND_HALF_UP));
            countDto.setShopId(shopId);
            countDto.setShopName(shopName);
            countDto.setShopImage(shopImage);


            countDto.setProducts(countProducts);
            countDto.setMemberId(memberId);
           // countDto.setSendAmount(new BigDecimal("0.00"));
            countDtos.add(countDto);
        }
        //组装最外层数据
        Double totalAmount = 0.00;
        Double payAmount =0.00;
        for(SundayCountDto countDto:countDtos){
            totalAmount+=countDto.getTotalAmount().doubleValue();
            payAmount+=countDto.getPayAmount().doubleValue();
        }
        countTotalDto=new SundayCountTotalDto(new BigDecimal(totalAmount).setScale(2,BigDecimal.ROUND_HALF_UP),
                new BigDecimal(payAmount).setScale(2,BigDecimal.ROUND_HALF_UP),
                cartIds,
                countDtos
                );
        return countTotalDto;
    }

    /**
     * 获取用户购物车的商品总数量
     * @param memberId  用户id
     * @return
     */
    public Integer getCartProductNum(Long memberId){
        Integer num = 0;
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("memberId",memberId);
        List<SundayCart> cartList = super.list(param);
        for(SundayCart cart : cartList){
            num += cart.getNum();
        }
        return num;
    }




}

